/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.RecommendationFacadeLocal;
import model.Recommendation;
import util.JsonReturnMsg;
import util.JsonReturnTable;

/**
 *
 * @author Randy
 */
@WebServlet(name = "RecommendationServlet", urlPatterns = {"/RecommendationServlet"})
public class RecommendationServlet extends HttpServlet {

    @EJB
    RecommendationFacadeLocal rFacade;
    Gson gson = new Gson();
    private String json;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            if (action.equals("getRecommendations")) {
                getRecommendations(request, response);

            } else if (action.equals("updateRecommendation")) {
                updateRecommendation(request, response);

            } else if (action.equals("createRecommendation")) {
                createRecommendation(request, response);

            } else if (action.equals("deleteRecommendation")) {
                deleteRecommendation(request, response);

            } else if (action.equals("getRecommendationInfo")) {
                getRecommendationInfo(request, response);
            }

        } catch (Exception ex) {
            json = gson.toJson(new JsonReturnMsg("Error", ex.getMessage(), "error"));
            response.getWriter().println(json);
        } finally {
            response.getWriter().close();
        }
    }

    private void getRecommendations(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String theme_id = request.getParameter("theme_id");

        ArrayList<Recommendation> rList = new ArrayList<Recommendation>();

        if (!theme_id.equals("")) {
            rList = rFacade.getRecommendations(Long.parseLong(theme_id));
        }

        json = gson.toJson(new JsonReturnTable(rList.size() + "", rList));
        response.getWriter().println(json);
    }

    private void getRecommendationInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String recommend_id = request.getParameter("recommend_id");

        Recommendation r = rFacade.getRecommendation(Long.parseLong(recommend_id));

        json = gson.toJson(r);
        response.getWriter().write(json);
    }

    private void updateRecommendation(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String theme = request.getParameter("theme");
        String recommend_id = request.getParameter("recommend_id");
        String shortDesc = request.getParameter("short");
        String longDesc = request.getParameter("long");
        String min = request.getParameter("min");
        String max = request.getParameter("max");

        boolean result = validateRange(Long.parseLong(theme), Double.parseDouble(min), Double.parseDouble(max), Long.parseLong(recommend_id));

        if (result) {
            rFacade.updateRecommendation(Long.parseLong(recommend_id), shortDesc, longDesc, Double.parseDouble(min), Double.parseDouble(max));
            json = gson.toJson(new JsonReturnMsg("Edit Recommendation", "Recommendation updated", "info"));

        } else {
            json = gson.toJson(new JsonReturnMsg("Edit Recommendation", "Overlapping with existing recommendation's range", "error"));
        }

        response.getWriter().println(json);
    }

    private void createRecommendation(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String theme = request.getParameter("theme");
        String shortDesc = request.getParameter("short");
        String longDesc = request.getParameter("long");
        String min = request.getParameter("min");
        String max = request.getParameter("max");

        boolean result = validateRange(Long.parseLong(theme), Double.parseDouble(min), Double.parseDouble(max), 0);

        if (result) {
            rFacade.createRecommendation(Long.parseLong(theme), shortDesc, longDesc, Double.parseDouble(min), Double.parseDouble(max));
            json = gson.toJson(new JsonReturnMsg("New Recommendation", "Recommendation created", "info"));

        } else {
            json = gson.toJson(new JsonReturnMsg("New Recommendation", "Overlapping with existing recommendation's range", "error"));
        }

        response.getWriter().println(json);
    }

    private boolean validateRange(Long theme, double min, double max, long recommend_id) {
        ArrayList<Recommendation> rList = rFacade.getRecommendations(theme);

        boolean result = true;

        if (!rList.isEmpty()) {
            for (Recommendation r : rList) {
                if (recommend_id != 0 && r.getId() == recommend_id) {
                    continue;
                } else {
                    if (min > r.getLower_range().doubleValue() && min < r.getUpper_range().doubleValue()) {
                        result = false;
                        break;

                    } else if (max > r.getLower_range().doubleValue() && max < r.getUpper_range().doubleValue()) {
                        result = false;
                        break;

                    } else if (min < r.getLower_range().doubleValue() && max > r.getUpper_range().doubleValue()) {
                        result = false;
                        break;

                    } else if (min > r.getLower_range().doubleValue() && max < r.getUpper_range().doubleValue()) {
                        result = false;
                        break;

                    } else if (min == r.getLower_range() && max != r.getUpper_range()) {
                        result = false;
                        break;
                    }
                }
            }
        }

        return result;
    }

    private void deleteRecommendation(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String theme_id = request.getParameter("theme_id");
        String recommend_id = request.getParameter("recommend_id");

        rFacade.deleteRecommendation(Long.parseLong(theme_id), Long.parseLong(recommend_id));

        json = gson.toJson(new JsonReturnMsg("Delete Recommendation", "Recommendation deleted", "info"));
        response.getWriter().println(json);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
